#include <errno.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <time.h>

#include <unistd.h>
typedef void (*AsyncCallback)(int fd, const char* buffer, ssize_t num_bytes);

void async_read(int fd, char* buffer, size_t buffer_size, AsyncCallback callback) {
    ssize_t num_bytes = read(fd, buffer, buffer_size);
    if (num_bytes > 0) {
        callback(fd, buffer, num_bytes);
    }
    else if (num_bytes == 0) {
        // 客户端关闭连接
        printf("Client closed the connection.\n");
    }
    else if (errno != EAGAIN) {
        // 读取错误
        perror("read");
    }
}

void async_write(int fd, const char* buffer, size_t buffer_size, AsyncCallback callback) {
    ssize_t num_bytes = write(fd, buffer, buffer_size);
    if (num_bytes > 0) {
        callback(fd, buffer, num_bytes);
    }
    else if (num_bytes == 0) {
        // 客户端关闭连接
        printf("Client closed the connection.\n");
    }
    else if (errno != EAGAIN) {
        // 写入错误
        perror("write");
    }
}

void read_callback(int fd, const char* buffer, ssize_t num_bytes) {
    printf("Received: %.*s\n", (int)num_bytes, buffer);

    // 在这里可以进行其他操作...

    // 继续异步读取
    char read_buffer[1024];
    async_read(fd, read_buffer, sizeof(read_buffer), read_callback);
}

void write_callback(int fd, const char* buffer, ssize_t num_bytes) {
    printf("Sent: %.*s\n", (int)num_bytes, buffer);

    // 在这里可以进行其他操作...

    // 继续异步写入
    const char* message = "Hello, client!";
    async_write(fd, message, strlen(message), write_callback);
}

int main() {
    int server_fd, client_fd;

    // 创建套接字
    server_fd = socket(AF_INET, SOCK_STREAM, 0);

    // 绑定和监听...

    // 接受连接请求
    client_fd = accept(server_fd, NULL, NULL);

    // 设置客户端套接字为非阻塞模式
    int flags = fcntl(client_fd, F_GETFL, 0);
    fcntl(client_fd, F_SETFL, flags | O_NONBLOCK);

    // 异步读取
    char read_buffer[1024];
    async_read(client_fd, read_buffer, sizeof(read_buffer), read_callback);

    // 异步写入
    const char* message = "Hello, client!";
    async_write(client_fd, message, strlen(message), write_callback);

    while (1) {
        // 在这里可以进行其他操作...

        usleep(1000);  // 短暂延迟，避免过于频繁的循环
    }

    // 关闭套接字
    close(client_fd);
    close(server_fd);

    return 0;
}
